/*
   Copyright (c) 2010 Bryce Alcock

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.com

 */

package com.ecocrypt.network.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Bryce.Alcock
 */
public class BlockingRandomClient {

    public static void main(String args[]){
        int threads = (args.length==1)?Integer.parseInt(args[0]):5;
        for(int i=0;i<threads;++i){
            try {
                ClientSender cs = new ClientSender(new Socket("localhost", 4000));
                cs.start();
            } catch (UnknownHostException ex) {
                Logger.getLogger(BlockingRandomClient.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(BlockingRandomClient.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    static class ClientSender extends Thread{

        Socket sock;
        InputStream is;
        OutputStream os;

        /**
         * If we can't create this object, we need to raise an exception immediately.
         *
         * @param socket is the socket that will be used for this sender.
         * @throws IOException
         */
        ClientSender(Socket s) throws IOException{
            
            sock = s;
            is=sock.getInputStream();
            os=sock.getOutputStream();

        }

        @Override
        public void run() {

            try {
                int sendbytes = (int) (Math.random()*1000 +1);
                for (int i = 0; i < sendbytes; ++i) {
                        os.write((byte) (Math.random()*1000%63 + 64 ));
                }
                while (is.read() > -1) {
                }
                is.close();
                os.close();
                sock.close();
            } catch (IOException ex) {
                Logger.getLogger(BlockingRandomClient.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}
